package com.sample.thread.toilet;

import java.util.SplittableRandom;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>Description: </p>
 *
 * @author zg
 * @version v1.0.0
 * @since 2024/8/22
 **/
public class Toilet {

    private Integer tId;
    //锁
    private Lock lock = new ReentrantLock(true);

    public Toilet(Integer depId) {
        this.tId = depId;
    }
    public void enter(Person person) {
        try {
            lock.lock();//拿锁（如果锁已被其他线程获取，则当前线程会被阻塞，直到获取到锁为止）
            //System.out.println("部门["+person.getDepId() +"]的"+ person.getEmpName() + "获得Toilet-"+this.tId+" 使用权，time:" + System.currentTimeMillis());
            int sec = new SplittableRandom().nextInt(1, 4);
            Thread.sleep(sec * 1000);//使用1-3秒
            System.out.println("部门["+person.getDepId() +"]的"+ person.getEmpName() + "获得-T"+this.tId+" 使用权，使用了:" + sec + "秒");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//释放锁（完事了，开门出去）
        }

    }

}
